//
//  WJChatVoicePanelCoverView.m
//  WJAgroManagerDemo
//
//  Created by tqh on 2020/4/14.
//  Copyright © 2020 tqh. All rights reserved.
//

#import "WJChatVoicePanelCoverView.h"
#import "UIColor+Hex.h"
#import "UIView+IM.h"
#import "EMAudioPlayerHelper.h"

@interface WJChatVoicePanelCoverView()

@property (nonatomic,strong) UIButton *playButton;
@property (nonatomic,strong) UILabel *timeLabel;
@property (nonatomic,strong) UIButton *sendButton;
@property (nonatomic,strong) UIButton *cancelButton;

@property (nonatomic ,strong) dispatch_source_t timer_gcd;  //GCD定时器
@property (nonatomic, assign) NSInteger currentTime;        //当前时间

@end

@implementation WJChatVoicePanelCoverView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.playButton];
        [self addSubview:self.timeLabel];
        [self addSubview:self.sendButton];
        [self addSubview:self.cancelButton];
    }
    return self;
}

- (void)layoutSubviews {
    
    self.playButton.frame = CGRectMake((self.width - 86)/2, 24, 86, 86);
    
    self.timeLabel.frame = CGRectMake(0, 10+self.playButton.bottom, self.width, 20);
    
    self.sendButton.frame = CGRectMake(40, self.height - 34 - 20, 107, 34);
    self.cancelButton.frame = CGRectMake(self.frame.size.width - 107 - 40, self.height - 34 - 20, 107, 34);
    self.sendButton.layer.cornerRadius = 34/2;
    self.cancelButton.layer.cornerRadius = 34/2;
}

#pragma mark - 事件监听

- (void)cancelButtonPressed {
    self.hidden = YES;
    [self _stopTimer];
    self.playButton.selected = NO;
    [[EMAudioPlayerHelper sharedHelper] stopPlayer];
    if (self.didItemBlock) {
        self.didItemBlock(1);
    }
}

- (void)sendButtonPressed {
    self.hidden = YES;
    [self _stopTimer];
    self.playButton.selected = NO;
    [[EMAudioPlayerHelper sharedHelper] stopPlayer];
    if (self.didItemBlock) {
        self.didItemBlock(0);
    }
}

- (void)playButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self _startTimer];
        [[EMAudioPlayerHelper sharedHelper] startPlayerWithPath:self.audioPath model:nil completion:^(NSError *error) {
            sender.selected = NO;
            [self _stopTimer];
        }];
    }else {
        [self _stopTimer];
        [[EMAudioPlayerHelper sharedHelper] stopPlayer];
    }
}

- (void)setAudioLength:(NSInteger)audioLength {
    _audioLength = audioLength;
    NSString *string = [self getMMSSFromSS:[NSString stringWithFormat:@"%ld",audioLength]];
    self.timeLabel.text = string;
}

#pragma mark - private

- (void)_startTimer
{
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            self.currentTime ++;
            NSString *time = [self getMMSSFromSS:[NSString stringWithFormat:@"%ld",self.currentTime]];
            self.timeLabel.text = time;
        });
        
         //4.开始执行
        dispatch_resume(timer);
        self.timer_gcd = timer;
}

- (void)_stopTimer
{
    self.playButton.selected = NO;
    NSString *string = [self getMMSSFromSS:[NSString stringWithFormat:@"%ld",self.audioLength]];
    self.timeLabel.text = string;
    self.currentTime = 0;
    if (self.timer_gcd) {
        dispatch_source_cancel(self.timer_gcd);
        self.timer_gcd = nil;
    }
}

- (NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
}

#pragma mark - 懒加载

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [UIButton new];
        [_playButton setImage:[UIImage imageNamed:@"WJChatVoicePanel_voice_play"] forState:UIControlStateNormal];
        [_playButton setImage:[UIImage imageNamed:@"WJChatVoicePanel_voice_pause"] forState:UIControlStateSelected];
        [_playButton addTarget:self action:@selector(playButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _playButton;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.textColor = [UIColor colorWithHexString:@"#4A4A4A"];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        _timeLabel.text = @"00:00";
    }
    return _timeLabel;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [UIButton new];
        _sendButton.backgroundColor = [UIColor colorWithHexString:@"#FFF1F6"];
        [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
        [_sendButton setTitleColor:[UIColor colorWithHexString:@"#EA3878"] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        _sendButton.layer.masksToBounds = YES;
    }
    return _sendButton;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton new];
        _cancelButton.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
        [_cancelButton setTitleColor:[UIColor colorWithHexString:@"#727171"] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.layer.masksToBounds = YES;
    }
    return _cancelButton;
}

@end
